﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.PlatformApi.Model;
using Refit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace DWF.Studio.PlatformApi
{
    public class PlatformApiHandler : IDisposable
    {
        private bool _isDisposed;

        private IPlatformApi _platformApi = null;

        private HttpClient _httpClient = null;

        public PlatformApiHandler(string uri)
        {
            _httpClient = RestService.CreateHttpClient(uri, new RefitSettings());
            _httpClient.DefaultRequestHeaders.ExpectContinue = false;

            _platformApi = RestService.For<IPlatformApi>(_httpClient);
        }

        public async Task<string> Login(string username, string password)
        {
            await Task.CompletedTask;

            return "robot a";
        }

        public async Task<UploadProcessResult> UploadProcess(string procid, string group, string name, string version, string fileName, string userName, Stream stream, string authorization ,string password="")
        {
            try
            {
                var result = await _platformApi.UploadProcessAsyncV2(procid, group, name, version, userName, password, new List<StreamPart>() { new StreamPart(stream, fileName) }, authorization);
                 
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 释放
        /// </summary>
        /// <param name="disposing"></param>
        private void Dispose(bool disposing)
        {
            if (!this._isDisposed)
            {
                if (disposing)
                {
                    this.OnDisposing();
                }
                this._isDisposed = true;
            }
        }

        private void OnDisposing()
        {
            _httpClient.Dispose();
        }

        ~PlatformApiHandler()
        {
            this.Dispose(false);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
